package com.thinkingcoder.tcrpc.core.balancer;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询负载均衡
 */
public class RoundRobinLoadBalancer<T> implements LoadBalancer<T> {

    AtomicInteger index = new AtomicInteger(0);

    @Override
    public T choose(List<T> providers) {
        if (providers == null || providers.isEmpty()) {
            return null;
        }
        // (index.getAndIncrement() & Integer.MAX_VALUE) 使用与运算，保证永远是正整数
        return providers.get((index.getAndIncrement() & Integer.MAX_VALUE) % providers.size());
    }
}
